package com.qujia.station.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qujia.common.exception.BaseException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.domain.ActivityCommodityRules;
import com.qujia.station.domain.Commodity;
import com.qujia.station.domain.MarketActivity;
import com.qujia.station.domain.Station;
import com.qujia.station.enums.AllOrPartType;
import com.qujia.station.enums.MarketActivityType;
import com.qujia.station.mapper.ActivityCommodityRulesMapper;
import com.qujia.station.mapper.MarketActivityMapper;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.MarketActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("marketActivityService")
@Slf4j
public class MarketActivityServiceImpl implements MarketActivityService {

    @Autowired
    private MarketActivityMapper marketActivityMapper;

    @Autowired
    private ActivityCommodityRulesMapper activityCommodityRulesMapper;

    @Autowired
    private IStationService stationService;


    @Override
    @Transactional
    public Long saveMarketActivity(MarketActivity marketActivity) {
        if(Objects.isNull(marketActivity.getStationId())){
            throw new BaseException("未选择门店");
        }
        if(MarketActivityType.SPECIAL_PRICE.getValue().equals(marketActivity.getMarketActivityType())){
            throw new BaseException("暂时不能设置特价活动");
        }
        Station station = stationService.selectStationById(marketActivity.getStationId());
        marketActivity.setStationName(station.getStationName());
        // 全部商品，不用修改
        if(AllOrPartType.ALL.getValue().equals(marketActivity.getAllOrPart())){
            if(Objects.isNull(marketActivity.getDiscountNum())){
                throw new BaseException("选择全部商品时,未指定折扣");
            }
            if(marketActivity.getDiscountNum() <= 0){
                throw new BaseException("商品折扣需要大于0");
            }
            // 全部 只要活动表保存记录 部分 才需要将部分商品保存到规则表
            return marketActivityMapper.insertSelective(marketActivity);
        } else if(CollectionUtils.isEmpty(marketActivity.getActivityCommodityRulesList())){
            throw new BaseException("选择部分商品时，未指定商品");
        }

        // 校验选择部分商品时，商品不能重复
        checkRepeat(marketActivity.getActivityCommodityRulesList());

        Long marketActivityId = 0L;
        synchronized (this) {
            long i = marketActivityMapper.insertSelective(marketActivity);
            if(i <= 0){
                throw new BaseException("新增活动失败");
            }
            marketActivityId = marketActivity.getMarketActivityId();
            for (ActivityCommodityRules activityCommodityRules : marketActivity.getActivityCommodityRulesList()) {
                if(MarketActivityType.DISCOUNT_NUM.getValue().equals(marketActivity.getMarketActivityType())
                        && activityCommodityRules.getDiscountNum() <= 0){
                    throw new BaseException("商品折扣需要大于0");
                }

                if(MarketActivityType.SPECIAL_PRICE.getValue().equals(marketActivity.getMarketActivityType())
                        && activityCommodityRules.getSpecialPrice().compareTo(BigDecimal.ZERO) <= 0){
                    throw new BaseException("商品特价需要大于0");
                }
                activityCommodityRules.setMarketActivityId(marketActivityId);
                activityCommodityRulesMapper.insertSelective(activityCommodityRules);
            }
        }
        return marketActivityId;
    }

    // 校验选择部分商品时，商品不能重复
    private void checkRepeat(List<ActivityCommodityRules> activityCommodityRulesList){
        List<ActivityCommodityRules> rulesList = activityCommodityRulesList.stream().filter(activityCommodityRules -> {
            if(Objects.nonNull(activityCommodityRules) && Objects.nonNull(activityCommodityRules.getCommodityId())){
                if(StringUtils.isEmpty(activityCommodityRules.getIsDeleted())){
                    return true;
                }else if("0".equals(activityCommodityRules.getIsDeleted())){
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());

        List<Long> commodityIdList = rulesList.stream().map(ActivityCommodityRules::getCommodityId).distinct().collect(Collectors.toList());
        if(rulesList.size() != commodityIdList.size()){
            throw new BaseException("选择部分商品时，商品不能重复");
        }
    }

    @Override
    public List<MarketActivity> selectMarketActivityList(MarketActivity marketActivity) {
        List<MarketActivity> marketActivities = marketActivityMapper.selectMarketActivityList(marketActivity);
        if(CollectionUtils.isEmpty(marketActivities)){
            return null;
        }
        for (MarketActivity activity : marketActivities) {
            // 判断状态
            String nowTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date());
            String beginTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,activity.getBeginTime());
            String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,activity.getEndTime());
            if("1".equals(activity.getIsEnabled())
                    && nowTime.compareTo(beginTime) >= 0 && endTime.compareTo(nowTime) >= 0){
                activity.setStatus("1");
            } else {
                activity.setStatus("0");
            }
            // 查询商品规则
            ActivityCommodityRules rules = new ActivityCommodityRules();
            rules.setMarketActivityId(activity.getMarketActivityId());
            List<ActivityCommodityRules> commodityRulesList = activityCommodityRulesMapper.selectActivityCommodityRulesList(rules);
            if(CollectionUtils.isNotEmpty(commodityRulesList)) {
                activity.setActivityCommodityRulesList(commodityRulesList);
            }
        }
        return marketActivities;
    }

    @Override
    public int updateMarketActivity(MarketActivity marketActivity) {
        boolean result = checkProgress(marketActivity.getMarketActivityId());
        if(result){
            throw new BaseException("该活动进行中，不能编辑");
        }
        if(Objects.nonNull(marketActivity.getStationId())){
            Station station = stationService.selectStationById(marketActivity.getStationId());
            if(Objects.nonNull(station)){
                marketActivity.setStationName(station.getStationName());
            }
        }
        // 更新活动信息
        int i = marketActivityMapper.updateByPrimaryKeySelective(marketActivity);
        if(i <= 0){
            return 0;
        }
        if(AllOrPartType.ALL.getValue().equals(marketActivity.getAllOrPart())){
            activityCommodityRulesMapper.deleteByMarketActivityId(marketActivity.getMarketActivityId());
            return i;
        }

        if(CollectionUtils.isEmpty(marketActivity.getActivityCommodityRulesList())){
            throw new BaseException("选择部分商品时，未指定商品");
        }
        // 校验选择部分商品时，商品不能重复
        checkRepeat(marketActivity.getActivityCommodityRulesList());

        // 判断是否是新增的商品
        for (ActivityCommodityRules activityCommodityRules : marketActivity.getActivityCommodityRulesList()) {
            if(Objects.nonNull(activityCommodityRules.getActivityCommodityId())){
                activityCommodityRulesMapper.updateByPrimaryKeySelective(activityCommodityRules);
            } else {
                activityCommodityRules.setMarketActivityId(marketActivity.getMarketActivityId());
                activityCommodityRulesMapper.insertSelective(activityCommodityRules);
            }
        }
        return i;
    }

    @Override
    public int deleteMarketActivity(Long marketActivityId) {
        boolean result = checkProgress(marketActivityId);
        if(result){
            throw new BaseException("该活动进行中，不能删除");
        }
        int i = marketActivityMapper.deleteByMarketActivityId(marketActivityId);
        if(i <= 0){
            return 0;
        }
        activityCommodityRulesMapper.updateByMarketActivityId(marketActivityId);
        return i;
    }

    // 判断某活动是否是进行中
    private boolean checkProgress(Long marketActivityId){
        MarketActivity marketActivity = marketActivityMapper.selectByPrimaryKey(marketActivityId);
        if("1".equals(marketActivity.getIsDeleted())){
            throw new BaseException("该活动已删除");
        }
        String beginTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,marketActivity.getBeginTime());
        String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,marketActivity.getEndTime());
        String now = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date());
        // 进行中
        if("1".equals(marketActivity.getIsEnabled())
                && (now.compareTo(beginTime) > 0) && (now.compareTo(endTime) < 0) ){
            return true;
        }
        return false;
    }

    @Override
    public List<MarketActivity> progressMarketActivityList(Commodity commodity) {
        String now = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date());
        MarketActivity marketActivity = new MarketActivity();
        marketActivity.setStationId(commodity.getStationId());
        marketActivity.setNowTime(now);
        marketActivity.setIsEnabled("1");
        return marketActivityMapper.progressMarketActivityList(marketActivity);
    }

    @Override
    public int updateEnabled(MarketActivity marketActivity) {
        return marketActivityMapper.updateEnabled(marketActivity);
    }

}
